<?php
namespace Admin\Controller;
use Admin\Controller\CommonController;

class ArticleController extends CommonController {
	/**
	 * 文章列表
	 * @return [type] [description]
	 */
	public function alist() {
        $title = I('get.title', '');
        $userName= I('get.username', '');
        $map = array();
        if($title) {
            $map['title'] = array("like","%{$title}%");
        }

        if($userName) {
            $map['realname'] = array("like","%{$userName}%");
        }

        $aModel = M('Article');
        $total = $aModel->alias('ar')
            ->join('__USER_INFO__ u ON u.uid=ar.user_id','left')->where($map)->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $articleList = $aModel->where($map)
        			 ->alias('ar')
        			 ->join('__USER_INFO__ u ON u.uid=ar.user_id','left')
        			 ->order('id DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        foreach($articleList as $k=>$v){
        	if($v['author']){
        		$a=M('User_info')->field('realname')->where("uid in ({$v['author']})")->select();
        		$s=array();
        		foreach($a as $kk=>$vv){
        			$s[]=$vv['realname'];
        		}
        		$articleList[$k]['author']=implode(',',$s);
        	}


        	if($v['deletetime']!=NULL){
        		$articleList[$k]['state']='用户删除';
        	}
        }

		if(IS_AJAX) {
			echo json_encode($articleList);
			exit;
		} else {
			$this->assign('showpage', $show);
			$this->assign('articleList', $articleList);
			$this->display();
		}

	}

	public function verify($id, $state) {
		$res = M('Article')->where(array('id' => $id))->save(array(
			'state' => $state,
		));

		if($res !== false) {
			$this->success('审核成功');	
		} else {
			$this->error('审核失败');
		}
	}

	public function ajaxDelArticle() {
		if(IS_GET) {
			$id = I('get.id');
		} elseif(IS_POST) {
			$id = I('post.id');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['id'] = array('in', $id);
		$res = M('Article')->where($map)->delete();
		if($res) {
			$imap['aid'] = array('in', $id);
			$attach = M('Attachment')->where($imap)->select();

			M('Attachment')->where($imap)->delete();

			foreach($attach as $val) {
				@unlink(UPLOAD_PATH . $val['filepath'] . $val['filename']);
			}


			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}


	public function ajaxGetArticle() {
		$aid = I('get.aid', 0);
		$info = M('Article')->where(array('id' => $aid))->find();
		$info['html_content'] = htmlspecialchars_decode($info['html_content']);

        if($info){
            $this->ajaxReturn($info);
        }else{
            $this->ajaxReturn(0);
        }
	}
	
	public function editArticle($id) {
		C('SHOW_PAGE_TRACE','true');
		if(IS_POST) {
			$dataGet['id'] = I('post.aid', 0);
			$dataGet['title'] = I('post.title', ''); // 文稿标题
			$dataGet['author'] = I('post.author', ''); // 文稿作者
			$dataGet['content'] = I('post.content', '', 'strip_tags'); // 文稿内容
			$dataGet['html_content'] = I('post.content', '');

			$articleModel = D('Article');
			if($articleModel->create($dataGet)) {
				$res = $articleModel->save($dataGet);
				if($res) {
					$this->success('文档修改成功');	
				} else {
					$this->error('文档修改失败');	
				}
			} else {
				$this->error($articleModel->getError());			
			}
		} else {
			$article=M('Article')->alias('ar')
			->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
			->find($id);

			$nameList=M('UserInfo')->where(array('uid'=>array('in',$article['author'])))->select();

			foreach ($nameList as $key => $value) {
				$name[]=$value['realname'];
			}
			$name=implode(',',$name);
			$article['authorlist']=$name;

			$attach=M('Attachment')->where(array('aid'=>$id,'attachstate'=>1))->select();

			$this->assign('attach',$attach);


			$this->assign('article',$article);
			$this->display();
		}

	}


	/**
	 * 前端上传图片配置
	 * @return [type] [description]
	 */
	public function getImageUploadConfig() {
		$action = I('get.action');

		switch ($action) {
			case 'uploadImage':
				$file = $this->_uploadAttach();
				if($file['upfile']) {
					$this->ajaxReturn(array('state' => 'SUCCESS', 'url' => '/Uploads' . $file['upfile']['savepath'] . $file['upfile']['savename']));
				} else {
					$this->ajaxReturn(array('state' => '上传失败'));
				}
				break;
			default:
				$config = array(
				    "imageActionName" => 'uploadImage', /* 执行上传图片的action名称 */
				    "imageFieldName" => "upfile", /* 提交的图片表单名称 */
				    "imageMaxSize" => 2048000, /* 上传大小限制，单位B */
				    "imageAllowFiles" => array(".png", ".jpg", ".jpeg", ".gif", ".bmp"), /* 上传图片格式显示 */
				    "imageCompressEnable" => true, /* 是否压缩图片,默认是true */
				    "imageCompressBorder" => 1600, /* 图片压缩最长边限制 */
				    "imageInsertAlign" => "none", /* 插入的图片浮动方式 */
				    "imageUrlPrefix" => "", /* 图片访问路径前缀 */
				    "imagePathFormat" => UPLOAD_PATH . "Image/{yyyy}/{mm}/{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */			
				);

				$this->ajaxReturn($config);
				break;
		}
	}

	/**
	 * 上传附件
	 * @return [type] [description]
	 */
	protected function _uploadAttach($type, $thumb = false,$name='') {
		$ext_arr = array(
                'Image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
                'Photo' => array('jpg', 'jpeg', 'png'),
                'Flash' => array('swf', 'flv'),
                'Media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
                'File' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
        );
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->saveRule = date('ymdHis', time()) . '_' . mt_rand(5);
        $upload->autoSub = true;//使用子目录保存上传文件
        $upload->subType = 'custom';//使用日期模式创建子目录
        $upload->subName = date('Y') . '/' . date('m') . '/' . date('d');
        $upload->dateFormat = 'Ymd';//设置子目录日期格式
        $upload->exts  = $ext_arr[$type];// 设置附件上传类型
        $upload->rootPath  =  UPLOAD_PATH;
        $upload->savePath =  $type . '/';// 设置附件上传目录
    
        // 上传文件
        $info   =   $upload->upload();

        if(!$info) {
		   return $upload->getError();
        }else{
        	if($thumb){
        		$image = new \Think\Image(); 
        		$image->open(UPLOAD_PATH . $info[$name]['savepath'].$info[$name]['savename']);
        		$image->thumb(160, 160,1)->save(UPLOAD_PATH . $info[$name]['savepath'].$info[$name]['savename']);
        		$info['thumbWidth']=$image->width(); 
        		$info['thumbHeight']=$image->height(); 
        		$info['size']=$image->size(); 
        	} 
		   return $info;
        }

	}

	function ajaxUploadImage(){
		$info=$this->_uploadAttach('Image', true,'indexFile');

		if($info){
			$this->ajaxReturn(array('status'=>1,'info'=>$info['indexFile']));
		}else{
			$this->ajaxReturn(array('status'=>0));
		}
	}

    /**
     *根据 I('get.start') 和 I('get.end') 查询文稿列表
     * @return null
     */
	private  function getQueryList(){
        if(IS_GET && I('get.queryTime')){

            $start=strtotime(I('get.queryTime')."-01 00:00:00");
            $end=strtotime('+1 month',$start)-1;

            $sql="SELECT
whtvjw_article.title title,
FROM_UNIXTIME(whtvjw_article.create_time,'%Y-%m-%d %H:%i') create_time,
whtvjw_user_info.realname realname,
whtvjw_user_info.mobile mobile,
whtvjw_channel.`name` jigou


FROM
whtvjw_article
LEFT JOIN whtvjw_user_info ON whtvjw_article.user_id = whtvjw_user_info.uid
LEFT JOIN whtvjw_channel ON whtvjw_user_info.userchannel = whtvjw_channel.chid
WHERE
whtvjw_article.state = 1
AND create_time>='{$start}' AND create_time<='{$end}' ORDER BY whtvjw_article.create_time ASC";

            $r=m()->query($sql);
            return $r;
        }else{
            return null;
        }
    }


    public function export(){
        if($r=$this->getQueryList()){
            $this->assign('art',$r);
        }
        $this->display();
    }

    public function excel(){
        if($r=$this->getQueryList()){
            echo $xlsName  = I('get.queryTime')."发稿列表";
            $xlsCell  = array(
                array('title','标题'),
                array('create_time','创建时间'),
                array('realname','姓名'),
                array('mobile','手机'),
                array('jigou','机构名称'),
            );

            exportExcel($xlsName,$xlsCell,$r);
        }else{
            echo 2;
            exit;
        }
    }


}